<template>
  <div class="box1">
    <div class="box1-1">
      <div class="box1-1-1" ref="leftBox">


        <img src="../assets/icon/头像.jpg" />

        <div style="position: relative;">
          <ul>

            <li style="margin: 0; position: absolute; right: -160px;">
              <img style="border-radius: 0; width: 150px; " v-if="addWx" src="../assets//icon/WxPicture.jpg">
            </li>

            <li>
              <img @mouseover="wxOpenPicture" @mouseout="wxClosePicture" style="border-radius: 0;"
                src="../assets/icon/WxLog.png" />
            </li>

            <li>
              <img @click="openGitee" @mouseover="gitEeOver" @mouseout="gitEeOut" style="border-radius: 10px;"
                src="../assets/icon/GitEe.jpg" />
              <p ref="gitP" style="color: aliceblue; margin: 0;">项目代码</p>
            </li>
          </ul>
        </div>

      </div>

      <div class="box1-1-2" ref="centerBox">
        <!-- 上面的搜索未写 -->
        <div
          style="width: 100%; height: 10%; background-color: rgb(30,32,41); margin-bottom: 10px; display: flex; flex-direction: row; justify-content: flex-end; align-items: center;">

        </div>

        <div class="hh" style="height: 88%; overflow: auto;">
          <div class="box1-1-2-1" v-for="i in 2"
            style="  display: flex; flex-direction: row; flex-wrap: nowrap; justify-content: flex-start;justify-content: space-between; align-items: center; font-size: 1px;">
            <div style="margin-left: 10px;">
              <img src="../assets/icon/头像.jpg" style="width: 40px; border-radius: 50%;">
            </div>
            <div style="display: flex; flex-direction: column; flex-wrap: wrap; align-items: flex-start;">
              <p style="margin: 0 0; color: aliceblue;">PigChat官方群</p>
              <p style="margin: 1px 0; color: darkgray;">这是哪头猪：hh</p>
            </div>
            <div style="color: darkgray;">12:11</div>
          </div>
        </div>
      </div>

      <div class="box1-1-3" ref="rightBox">
        <div
          style="width: 100%; height: 10%; background-color: rgb(30,32,41); margin-bottom: 10px; display: flex; flex-direction: row; justify-content: flex-end; align-items: center;">
          <!-- 中间的人名 -->
          <div style="color: aliceblue; font-size: 30px; position: relative; right: 40%;">聊天室</div>
          <!-- 旁边的收起侧边栏 -->
          <div class="box1-1-4-1" @click="closeSidebar">
            <p>{{ sidebarStatus }}</p>
          </div>
        </div>
        <div class="box1-1-3-1" ref="chatContent">

          <!-- 
          <div class="chat-item-left" style="margin-bottom: 10px">
            <div style="margin-right: 10px">
              <img src="https://img1.baidu.com/it/u=2961575590,2057372040&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=500"
                alt="登录" style="border-radius: 50%; width: 65px" />
            </div>
            <div style="display: flex; flex-direction: column">
              <div>这是那头猪？</div>
              <div style="
                  width: 90%;
                  height: 100%;
                  background-color: darkgoldenrod;
                  border-radius: 20px;
                  padding: 8px;
                ">
                不想上班可能是因为工作的压力、不喜欢的工作内容、与同事关系不好、缺乏动力等原因。以下是一些建议帮助你处理这种情况：
                1.
                了解自己的需求和目标：思考你对工作的期望和目标是什么，是否与当前的工作环境相符合。如果发现自己对工作的期待与现实有较大差距，可能需要考虑寻找新的职业或调整工作方向。
                2.
                沟通与寻求支持：如果你感到压力过大或对工作内容不满意，与上级或同事进行沟通是一个好的选择。他们可能能够提供建议或帮助解决问题。同时，寻求家人、朋友或专业咨询师的支持也能帮助你缓解压力和找到解决方案。
                3.
                寻找工作的乐趣：尽量将工作中的任务与兴趣结合起来，找到其中的乐趣。尝试寻找能够激发你的激情和动力的方面，并将其融入工作中。
                4.
                做好自我管理：寻找适合自己的管理方式，如设立工作目标、制定合理的计划和优先事项等。合理规划时间和任务，避免过度压力。
                5.
                寻求职业发展机会：如果感到工作乏味或停滞不前，尝试主动寻找职业发展的机会，如参加培训课程、进修学习、跳槽等。持续学习和发展能够增加工作的挑战性和满足感。
                6.
                寻找工作之外的乐趣：将注意力放在工作之外的爱好和兴趣上，保持身心的平衡。享受与家人朋友相处、锻炼身体、追求个人爱好的时间，能够帮助你更好地应对工作中的压力。
                最重要的是要知道，职业生涯中遇到困难和挑战是正常的。时刻保持积极的心态和灵活的思维，不断探索和适应，有助于找到更合适和满意的工作。
              </div>
            </div>
          </div>
 -->


          <!-- <div
            class="chat-item-right"
            style="margin-bottom: 10px"
          >
            <div
              style="
                display: flex;
                flex-direction: column;
                align-items: flex-end;
              "
            >
              <div style="text-align: right">这是那头猪？</div>
              <div
                style="
                  width: 90%;
                  height: 100%;
                  background-color: darkgoldenrod;
                  border-radius: 20px;
                  padding: 8px;
                "
              >
                不想上班可能是因为工作的压力、不喜欢的工作内容、与同事关系不好、缺乏动力等原因。以下是一些建议帮助你处理这种情况：
                1.
                了解自己的需求和目标：思考你对工作的期望和目标是什么，是否与当前的工作环境相符合。如果发现自己对工作的期待与现实有较大差距，可能需要考虑寻找新的职业或调整工作方向。
                2.
                沟通与寻求支持：如果你感到压力过大或对工作内容不满意，与上级或同事进行沟通是一个好的选择。他们可能能够提供建议或帮助解决问题。同时，寻求家人、朋友或专业咨询师的支持也能帮助你缓解压力和找到解决方案。
                3.
                寻找工作的乐趣：尽量将工作中的任务与兴趣结合起来，找到其中的乐趣。尝试寻找能够激发你的激情和动力的方面，并将其融入工作中。
                4.
                做好自我管理：寻找适合自己的管理方式，如设立工作目标、制定合理的计划和优先事项等。合理规划时间和任务，避免过度压力。
                5.
                寻求职业发展机会：如果感到工作乏味或停滞不前，尝试主动寻找职业发展的机会，如参加培训课程、进修学习、跳槽等。持续学习和发展能够增加工作的挑战性和满足感。
                6.
                寻找工作之外的乐趣：将注意力放在工作之外的爱好和兴趣上，保持身心的平衡。享受与家人朋友相处、锻炼身体、追求个人爱好的时间，能够帮助你更好地应对工作中的压力。
                最重要的是要知道，职业生涯中遇到困难和挑战是正常的。时刻保持积极的心态和灵活的思维，不断探索和适应，有助于找到更合适和满意的工作。
              </div>
            </div>

            <div style="margin-right: 10px">
              <img
                src="https://img1.baidu.com/it/u=2961575590,2057372040&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=500"
                alt="登录"
                style="border-radius: 50%; width: 65px"
              />
            </div>
          </div> -->


        </div>

        <div class="chat-edit">
          <el-input v-model="textarea1" :autosize="{ minRows: 2, maxRows: 2 }" type="textarea" placeholder="Please input"
            @keyup.enter="enterKeySendMessage" />
          <el-button type="success" round @click="clickSendMessage">send</el-button>
        </div>
      </div>

      <div class="box1-1-4" v-show="openSidebar">
        <!-- 上面的搜索未写 -->
        <div
          style=" width: 100%; height: 10%; background-color: rgb(30,32,41); display: flex; flex-direction: row; justify-content: space-around; align-items: center;">
          <p style="color: aliceblue;">在线人数: {{number}}</p>
        </div>

        <div class="hh" style="height: 90%; overflow: auto; background-color: rgb(72,77,95);">

          <div v-for="(value, key) in userInfoList" style=" display: flex; flex-direction: column; align-items: center; align-content: space-around;">

            <div ref="userList"  @mouseover="ULS" @mouseout="ULO" class="box1-1-2-1" 
              style=" display: flex; flex-flow: row nowrap; justify-content: flex-start; align-items: center; font-size: 1px;">
              <div style="margin-left: 20%; margin-right: 20px; position: relative;">
                <img :src="value.userImg" style="width: 40px; border-radius: 50%;">
                <span
                  style=" width: 20px; height: 20px; background-color: rgb(5,182,17); border-radius: 50%; display: inline-block; position: absolute; right: -7px; bottom: 3px;"></span>
              </div>
              <div style="display: flex; flex-direction: column; flex-wrap: wrap; align-items: flex-start;">
                <p style="margin: 1px 0; color: darkgray;">{{ value.userName }}</p>
              </div>
            </div>
          </div>

        </div>

      </div>
    </div>
  </div>
</template>

<script setup>
import { ref , reactive , onMounted , onBeforeUnmount} from "vue";

const textarea1 = ref("");
const chatContent = ref(null);
const openSidebar = ref("true");
const sidebarStatus = ref("<<")

const leftBox = ref(null);
const centerBox = ref(null);
const rightBox = ref(null);
const addWx = ref(false);
const gitP = ref(null);
const userList = ref(null);

const number = ref(0);

const userInfoList = reactive([]);

let socket;
let userName;
let userImg;
let userImgListUrl = 'https://image.baidu.com/search/acjson?tn=resulttagjson&logid=11319045315262352491&ie=utf-8&fr=&word=%E7%8C%AA%E7%8C%AA%E4%BE%A0%E5%9B%BE%E7%89%87%E9%BB%91%E6%9A%97%E4%B9%8B%E7%8E%8B&ipn=r&fm=index&pos=history&queryWord=%E7%8C%AA%E7%8C%AA%E4%BE%A0%E5%9B%BE%E7%89%87%E9%BB%91%E6%9A%97%E4%B9%8B%E7%8E%8B&cl=2&lm=-1&oe=utf-8&adpicid=&st=-1&z=&ic=&hd=&latest=&copyright=&s=&se=&tab=&width=&height=&face=0&istype=2&qc=&nc=1&expermode=&nojc=&isAsync=true&pn=30&rn=30&itg=1&gsm=1e&1690529015422=';

onMounted(() => {
  // 获取随机用户名
  userName = generateFullName();
  // 获取随机用户头像
  userImg = checkUserImg();
  // 初始化websocket连接
  init();
})

onBeforeUnmount(() => {
  destroy();
})

function init(){
  const socketUrl = 'ws:localhost:7878/websocket/'+ userName;
  // const socketUrl = 'ws:192.168.0.28:7878/websocket/'+ userName;
  // const socketUrl = 'ws:111.180.193.78:7878/websocket/'+ userName;
  socket = new WebSocket(socketUrl);

  socket.onopen = function() {
  // 连接建立时触发
  console.log("连接已经建立");
  socket.send(JSON.stringify({"userImg": userImg, "userName": userName}))
};

socket.onmessage = function(event) {
  // 接收到消息时触发
  const message = event.data;
  console.log(message);
  var date = JSON.parse(message);
  console.log(date);
  number.value = date.number;

  if ('from' in date) {
    if(date.from != userName){
    sendLeftMessage(date.from, date.img, date.info);
    const container = chatContent.value
    container.scrollTo({ top: container.scrollHeight, behavior: 'smooth' })
    }
  }

  if('userImg' in date && 'userName' in date && 'number' in date){
    number.value = date.number;
    userInfoList.push(date);

  }
};

socket.onerror = function(error) {
  // 发生错误时触发
  console.log(error);
};

socket.onclose = function(event) {
  // 连接关闭时触发
  console.log(event.data);
};
}

function destroy() {
  socket.close();
  console.log("连接已经关闭");
}

// 点击发送时发送消息的方法
function clickSendMessage() {
  sendMessage();
}

// 键盘弹起时发送消息
function enterKeySendMessage() {
  sendMessage();
}

// 发送消息的封装
function sendMessage() {
  var from = userName;
  var img = userImg;
  var messageInfo = textarea1.value;
  if (/^\s*$/.test(messageInfo)) {
    ElMessage({
    message: '请输入正确的消息内容',
    type: 'warning',
  })
    return;
  }
  // messageInfo = messageInfo.trim();

  // 本地发送消息
  sendRightMessage(from, img, messageInfo);

  var message = {
    from: userName,
    to : null,
    img: userImg,
    info: messageInfo
  }

  // 推送给远程java服务
  socket.send(JSON.stringify(message));

  // 注释模拟发送消息

  // if (textarea1.value === '' || textarea1.value.startsWith("\n")) {
  //   ElMessage.warning({
  //     message: "请输入要发送的消息",
  //   });
  //   // alert("请输入要发送的消息");
  //   textarea1.value = "";
  //   return;
  // }
  // var aa = parseInt(Math.random()*10);
  // if (aa % 2 === 0) {
  //     sendLeftMessage(from, img, message);
  // } else {
  //   sendRightMessage(from, img, message);
  // }


  // 设置滚动条的位置到最下面
  const container = chatContent.value
  // 清空iput框的内容
  textarea1.value = "";
  container.scrollTo({ top: container.scrollHeight, behavior: 'smooth' })
}

// 向左边发送消息
function sendLeftMessage(from, img, mesage) {
  var leftMessage = `
          <div class="chat-item-left" 
               style="margin-bottom: 10px; display: flex; justify-content: flex-start; align-items: flex-start; flex-direction: row;" v-for="i in 2">

              <div style="margin-right: 10px">
                <img
                  src="${img}"
                  alt="图片实效"
                  style="border-radius: 50%; width: 65px; height: 65px;"
                />
              </div>

              <div style="display: flex; flex-direction: column">
                <div style="color: yellow;">${from}</div>
                <div
                  style="
                    width: 90%;
                    height: 100%;
                    background-color: #6eab5f;
                    border-radius: 20px;
                    padding: 8px;
                    text-align: center;
                    color: unset;
                    font-size: 22px;
                    text-align: left
                  "
                >
                  ${mesage}
                </div>
              </div>
          </div> `;
  const parser = new DOMParser()
  const newElement = parser.parseFromString(leftMessage, 'text/html').body.firstChild
  chatContent.value.appendChild(newElement)
}

// 向右边发送消息
function sendRightMessage(from, img, mesage) {
  var rightMessage = `
    <div class="chat-item-right" style="margin-bottom: 10px; display: flex; flex-direction: row; justify-content: flex-end; align-items: flex-start;">
    <div style="
                  display: flex;
                  flex-direction: column;
                  align-items: flex-end;
                ">
        <div style="text-align: right; color: darkgray; white-space: nowrap;">${from}</div>
        <div style="
                    width: 90%;
                    height: 100%;
                    background-color: #777571;
                    border-radius: 20px;
                    padding: 8px;
                    text-align: center;
                    color: white;
                    font-size: 22px;
                    text-align: left
                  ">
            ${mesage}
        </div>
    </div>

    <div style="margin-right: 10px">
        <img src="${img}" alt="头像失效" style="border-radius: 50%; width: 65px; height: 65px" />
    </div>
    </div> `;
  const parser = new DOMParser()
  const newElement = parser.parseFromString(rightMessage, 'text/html').body.firstChild
  chatContent.value.appendChild(newElement)
}



// 切换侧边栏的状态
function closeSidebar() {
  // 切换侧边栏状态
  openSidebar.value = !openSidebar.value
  // 切换箭头的方向
  if (openSidebar.value == true) {
    leftBox.value.setAttribute('style', 'width: 10%');
    centerBox.value.setAttribute('style', 'width: 15%');
    rightBox.value.setAttribute('style', 'width: 60%');
    sidebarStatus.value = "<<";
  } else {
    // 修改各个盒子的宽度百分比
    leftBox.value.setAttribute('style', 'width: 10%');
    centerBox.value.setAttribute('style', 'width: 15%');
    rightBox.value.setAttribute('style', 'width: 75%');
    sidebarStatus.value = ">>";
  }
}

// 鼠标初到微信图片时触发
function wxOpenPicture() {
  addWx.value = true;
}
// 鼠标移除微信图片时触发
function wxClosePicture() {
  addWx.value = false;
}
// 点击打开gitee
function openGitee() {
  window.location.href = "https://gitee.com/koi_pig/PigChat?_from=gitee_search";
}
// 移入gitee
function gitEeOver() {
  gitP.value.setAttribute("style", "color: red; margin: 0;")
}
// 移除gitee
function gitEeOut() {
  gitP.value.setAttribute("style", "color: aliceblue; margin: 0;");
}

function ULS() {
  userList.value.setAttribute("style", "background-color: lightslategrey;display: flex; flex-flow: row nowrap; justify-content: flex-start; align-items: center; font-size: 1px;");
}

function ULO(){
  userList.value.setAttribute("style", "background-color: rgb(72, 77, 95);display: flex; flex-flow: row nowrap; justify-content: flex-start; align-items: center; font-size: 1px;");
}

// 随机生成中文姓氏
function generateSurname() {
  const surnames = ["赵", "钱", "孙", "李", "周", "吴", "郑", "王",
                    "冯", "陈", "楮", "卫", "蒋", "沈", "韩", "杨",
                    "朱", "秦", "尤", "许", "何", "吕", "施", "张",
                    "孔", "曹", "严", "华", "金", "魏", "陶", "姜",
                    "戚", "谢", "邹", "喻", "柏", "水", "窦", "章",
                    "云", "苏", "潘", "葛", "奚", "范", "彭", "郎",
                    "鲁", "韦", "昌", "马", "苗", "凤", "花", "方",
                    "俞", "任", "袁", "柳", "邓", "鲍", "史", "唐",
                    "费", "廉", "岑", "薛", "雷", "贺", "倪", "汤"];
  const randomIndex = Math.floor(Math.random() * surnames.length);
  return surnames[randomIndex];
}

// 随机生成中文名字
function generateGivenName() {
  const givenNames = ["伟", "芳", "娜", "秀英", "敏", "静", "丽", "强",
                      "磊", "洋", "艳", "勇", "军", "霞", "平", "刚",
                      "桂英", "明", "健", "红", "兰", "云", "华", "巧",
                      "俊", "婷", "辉", "英", "华", "莹", "慧", "巧",
                      "美", "俊", "婷", "辉", "英", "华", "莹", "慧"];
  const randomIndex1 = Math.floor(Math.random() * givenNames.length);
  const randomIndex2 = Math.floor(Math.random() * givenNames.length);
  const randomIndex3 = Math.floor(Math.random() * givenNames.length);
  return givenNames[randomIndex1] + givenNames[randomIndex2] + givenNames[randomIndex3];
}

// 随机生成三字姓名
function generateFullName() {
  const surname = generateSurname();
  const givenName = generateGivenName();
  return surname + givenName;
}

// 随机获取用户头像
function checkUserImg() {
 var list = [
  "https://img2.baidu.com/it/u=2712608978,2827236184&fm=253&fmt=auto&app=138&f=JPEG?w=576&h=324",
  "https://img2.baidu.com/it/u=757600384,1225901794&fm=253&fmt=auto&app=138&f=JPEG?w=448&h=252",
  "https://img2.baidu.com/it/u=935364193,1185230307&fm=253&fmt=auto&app=138&f=JPEG?w=889&h=500",
  "https://img1.baidu.com/it/u=527197400,3639052801&fm=253&fmt=auto&app=138&f=JPEG?w=864&h=486"
 ];
 return list[(Math.floor(Math.random() * 4) + 1) -1]
}


</script>

<style scoped>
.box1 {
  width: 100%;
  height: 100vh;
  background-image: url("https://img1.baidu.com/it/u=3441379051,416032584&fm=253&fmt=auto&app=138&f=JPEG?w=889&h=500");
  background-size: cover;
  background-repeat: no-repeat;
  background-position: center;
  display: flex;
  justify-content: center;
  align-items: center;
}

.box1-1 {
  width: 80%;
  height: 80%;
  background-color: rgb(39, 42, 55);
  border-radius: 30px;
  display: flex;
  justify-content: space-between;
}

.box1-1-1 {
  width: 10%;
  height: 100%;
  /* background-color: #8b2f73; */

  padding: 10px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-direction: column;
}

.box1-1-2 {
  width: 15%;
  height: 100%;
  /* background-color: #3e638d; */
}

.box1-1-3 {
  width: 60%;
  background-color: rgb(50, 54, 68);
}

.box1-1-3-1 {
  width: 100%;
  height: 79%;
  overflow: auto;
}

.hh::-webkit-scrollbar,
.box1-1-3-1::-webkit-scrollbar {
  width: 10px;
  /* 设置垂直滚动条的宽度 */
  height: 10px;
  /* 设置水平滚动条的高度 */
}

.hh-webkit-scrollbar-thumb,
.box1-1-3-1::-webkit-scrollbar-thumb {
  background-color: #888;
  /* 设置滚动条的颜色 */
}

.hh::-webkit-scrollbar-thumb:hover,
.box1-1-3-1::-webkit-scrollbar-thumb:hover {
  background-color: #555;
  /* 鼠标悬停时的滚动条颜色 */
}

.box1-1-4 {
  width: 20%;
  height: 100%;
  /* background-color: #823b43; */
}

.box1-1-1 {
  padding: 10px;
  border-radius: 10px;
  box-sizing: border-box;
}

.box1-1-2,
.box1-1-3 {
  border-radius: 10px;
  box-sizing: border-box;
}

.box1-1-1 img {
  border-radius: 50%;
  width: 65px;
}

ul {
  list-style: none;
  padding-inline-start: 0px;
}

.box1-1-2-1 {
  width: 100%;
  height: 10%;
  background-color: rgb(72, 77, 95);
  border-radius: 8px;
  margin-bottom: 10px;
}

.chat-item-left {
  display: flex;
  justify-content: flex-start;
  align-items: flex-start;
  flex-direction: row;
}

.chat-item-right {
  display: flex;
  align-items: flex-start;
  flex-direction: row;
}

.chat-edit {
  margin-top: 6px;
  max-height: 8%;

  display: flex;
  flex-direction: row;
  align-items: center;
}

.el-button {
  margin-left: 5px;
  height: 50px;
}

.box1-1-4-1 {
  width: 50px;
  height: 100%;
  color: aliceblue;
  font-size: 30px;
  border-radius: 10px;
  text-align: center;
  float: right;
  position: relative;
  display: flex;
  flex-direction: column;
  align-content: center;
  justify-content: center;
  align-items: center;
}

ul li:not(:last-child) {
  margin-bottom: 10px;
}
</style>
